<!-- 用户管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="5">
      <!-- 部门树 -->
      <el-col :lg="5" :xs="24">
        <setting-tree v-model="queryParams" @node-click="handerNodeClick" />
      </el-col>

      <!-- 问题列表 -->
      <el-col :lg="19" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="标题">
              <el-input v-model="queryParams.remark" placeholder="请输入标题查询" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery"><i-ep-search />搜索</el-button>
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button v-if="leaf" type="success" @click="openDialog()"><i-ep-plus />新增</el-button>
                <el-button type="danger" :disabled="removeIds.length === 0"
                  @click="handleDelete()"><i-ep-delete />删除</el-button>
              </div>
            </div>
          </template>

          <el-table v-loading="loading" :data="pageData" class="fix-table" fixed
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column key="bridgeType" label="专家类型" align="center" width="120" prop="bridgeType">
              <template #default="scope">
                <dictionary v-model="scope.row.bridgeType" type="tag" :data="bridgeOptions" />
              </template>
            </el-table-column>
            <el-table-column key="category" label="所属菜单" align="center" width="120" prop="category">
              <template #default="scope">
                <dictionary v-model="scope.row.category" type="tag" :data="categoryOptions" />
              </template>
            </el-table-column>
            <el-table-column key="diseaseTypeName" label="病害类型" align="center" width="120" prop="diseaseTypeName" />
            <el-table-column label="详情" min-width="120" align="center" prop="remark" />

            <el-table-column label="操作" fixed="right" width="220">
              <template #default="scope">
                <el-button type="primary" link size="small" @click="openDialog(scope.row)"><i-ep-edit />编辑</el-button>
                <el-button type="danger" link size="small"
                  @click="handleDelete(scope.row.id)"><i-ep-delete />删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-model:total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
            @pagination="handleQuery" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" :width="dialog.width" append-to-body draggable
      @close="closeDialog">
      <!-- 用户新增/编辑表单 -->
      <el-form ref="questionFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="专家类型" prop="bridgeType">
          <dictionary v-model="formData.bridgeType" :data="bridgeOptions" />
        </el-form-item>

        <el-form-item label="所属菜单" prop="category">
          <dictionary v-model="formData.category" :data="categoryOptions" @change="getDiseaseType" />
        </el-form-item>

        <el-form-item label="病害类型" prop="diseaseType">
          <el-select v-model="formData.diseaseType" placeholder="请输入病害类型">
            <el-option v-for="option in diseaseTypeOptions" :key="option.type" :label="option.name"
              :value="option.type" />
          </el-select>
        </el-form-item>

        <el-form-item label="问题描述" prop="remark">
          <el-input v-model="formData.remark" type="textarea" maxlength="200" placeholder="请输入问题描述"
            :autosize="{ minRows: 2, maxRows: 4 }" />
        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "User",
  inheritAttrs: false,
});

import settingTree from "./components/setting-tree.vue";
import { listBridge } from "@/api/ai/bridge/index";
import { DictForm } from "@/api/dict/types";
import {
  listQuestion,
  deleteQuestion,
  saveQuestion,
  getQuestionForm,
} from "@/api/ai/question/index";
import {
  QuestionForm,
  QuestionQuery,
  QuestionVO,
} from "@/api/ai/question/types";
import useDictionary from "@/components/Dictionary/dict";
import { DiseaseTypeVO } from "@/api/ai/disease-type/types";
import { listDiseaseType } from "@/api/ai/disease-type/index";

const useDict = useDictionary();
// 一级分类
const bridgeOptions = ref<DictForm[]>([]);
// 二级分类
const categoryOptions = useDict.getData("category");
// 三级分类, 每个菜单下都不同
const diseaseTypeOptions = ref<DiseaseTypeVO[]>([]);

const queryFormRef = ref(ElForm); // 查询表单
const questionFormRef = ref(ElForm); // 用户表单

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<QuestionQuery>({
  pageNo: 1,
  pageSize: 10,
  bridgeType: "1",
  category: "1",
});

const total = ref(0); // 数据总数
const pageData = ref<QuestionVO[]>(); // 用户分页数据

// 弹窗对象
const dialog = reactive({
  visible: false,
  width: 800,
  title: "",
});

// 表单数据
const formData = reactive<QuestionForm>({});
// 是否点击了叶子节点
const leaf = ref<boolean>(false);

// 校验规则
const rules = reactive({
  bridgeType: [
    { required: true, message: "桥梁类型不能为空", trigger: "blur" },
  ],
  category: [{ required: true, message: "所属菜单不能为空", trigger: "blur" }],
  remark: [{ required: true, message: "问题描述不能为空", trigger: "blur" }],
});

/** 查询 */
function handleQuery(value?: any) {
  loading.value = true;
  // 更新值
  const param = Object.assign(queryParams, value || {});
  listQuestion(param)
    .then(({ data }) => {
      pageData.value = data.records;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handerNodeClick(value?: any, isLeaf?: boolean) {
  leaf.value = isLeaf;
  handleQuery(value);
}

/** 重置查询 */
function resetQuery() {
  queryParams.pageNo = 1;
  queryParams.remark = undefined;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 * @param id 用户ID
 */
async function openDialog(row?: QuestionVO) {
  dialog.visible = true;
  getDiseaseTypeApi(queryParams);

  if (row) {
    getQuestionForm(row.id).then(({ data }) => {
      dialog.title = "修改病害";
      Object.assign(formData, { ...data });
    });
  } else {
    formData.bridgeType = queryParams.bridgeType;
    formData.category = queryParams.category;
    formData.diseaseType = queryParams.diseaseType;
    dialog.title = "新增病害";
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 */
function closeDialog() {
  dialog.visible = false;

  questionFormRef.value.resetFields && questionFormRef.value.resetFields();
  questionFormRef.value.clearValidate && questionFormRef.value.clearValidate();

  formData.id = undefined;
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  questionFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      saveQuestion(formData)
        .then(() => {
          if (userId) {
            ElMessage.success("修改成功");
          } else {
            ElMessage.success("新增成功");
          }
          closeDialog();
          resetQuery();
        })
        .finally(() => (loading.value = false));
    }
  });
}, 3000);

/** 删除 */
function handleDelete(id?: string) {
  const ids = id ? [id] : removeIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除问题?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteQuestion(ids).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

// 获取桥型
function getBridge() {
  listBridge().then(({ data }) => {
    bridgeOptions.value = data;
  });
}

function getDiseaseType() {
  getDiseaseTypeApi(null);
}

// 下拉列表
function getDiseaseTypeApi(data) {
  let params = {
    bridgeType: formData.bridgeType,
    category: formData.category,
  };
  if (data) {
    // 二级不选不显示第三级
    if (!data.category) {
      return;
    }
    params = {
      bridgeType: data.bridgeType,
      category: data.category,
    };
  }
  listDiseaseType(params).then(({ data }) => {
    diseaseTypeOptions.value = data;
  });
}

onMounted(() => {
  getBridge();
  handleQuery();
});
</script>

<style lang="scss" scoped>
$varTopPanel: 222px;

.fix-table {
  height: calc(var(--body-height) - $varTopPanel);
}
</style>
